package utils

import (
	"encoding/base64"
	"fmt"
	"os"
	"strings"
)

var (
	UploadDir = "./"
)

func UploadBase64(base64Data string, dir, filename string) (url string, err error) {
	// 提取真正的 base64 编码部分
	parts := strings.Split(base64Data, ",")
	if len(parts) < 2 {
		return "", fmt.Errorf("Invalid base64 data format")
	}
	realBase64Data := parts[1]
	var decoded []byte
	decoded, err = base64.StdEncoding.DecodeString(realBase64Data)
	if err != nil {
		return
	}
	url = dir
	fmt.Println("准备创建目录", UploadDir+url)
	_, err = os.Stat(UploadDir + url)
	if os.IsNotExist(err) {
		// 目录不存在，创建目录
		err = os.MkdirAll(UploadDir+url, 0664)
		if err != nil {
			fmt.Printf("创建%s目录失败:%s  \n", UploadDir+url, err)
			return
		}
	}
	if strings.Contains(parts[0], "png") {
		url += filename + ".png"
	} else if strings.Contains(parts[0], "jpeg") {
		url += filename + ".jpg"
	} else if strings.Contains(parts[0], "jpg") {
		url += filename + ".jpg"
	} else if strings.Contains(parts[0], "gif") {
		url += filename + ".gif"
	} else {
		return "", fmt.Errorf("只允许上传png和jpg图片")
	}
	err = os.WriteFile(UploadDir+url, decoded, 0664)
	if err != nil {
		fmt.Printf("WriteFile %s 失败:%s  \n", UploadDir+url, err)
	}
	return
}
